import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast";
const computedBehavior = require('miniprogram-computed').behavior
const app = getApp()
// 检查是否可提交定时器
let checkTime = null,
  // 验证码倒计时定时器
  codeTime = null;
import {
  ajaxSendMessage,
  ajaxGetTelUsers
} from '../../../api/registerLogin'
import {
  pageLanguage
} from '../../../language/registerLogin/index'
Page({
  behaviors: [computedBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    //自定义导航高度
    customNavHeight: app.globalData.customNavInfo.navHeight,
    baseURL: app.globalData.config.baseURL,
    // 表单数据
    formData: {
      // surnames: '',
      // name: '',
      k1UserId: null,
      tel: '',
      msgCode: ''
    },
    // 验证码倒计时
    codeNum: 0,
    // 同意协议
    isAgreement: false,
    // 是否能提交
    isSubmit: false,
    // 当前语言
    currentLanguage: app.globalData.language,
    // 页面国际化数据
    languageData: JSON.parse(JSON.stringify(pageLanguage[app.globalData.language].formPage)),
    // 选择账号弹层
    accountLayer: {
      show: false
    },
    // 多账号数据
    userList: []
  },
  watch: {
    'formData.**,isAgreement': function (formData, isAgreement) {
      if (checkTime) {
        clearTimeout(checkTime)
      }
      checkTime = setTimeout(() => {
        let {
          result
        } = this.isCheck();
        this.setData({
          isSubmit: result
        })
      }, 100)
    },
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {},
  // 空事件
  nullEvent() {},
  // 选择用户
  choiceUser(e) {
    let {
      index
    } = e.currentTarget.dataset,
      user = this.data.userList[index];
    this.closeAccountLayer();
    this.setData({
      'formData.k1UserId': user.k1UserId
    })
    this.submit();
  },
  // 关闭选择账号弹层
  closeAccountLayer() {
    this.setData({
      'accountLayer.show': false,
      'formData.k1UserId': null
    })
  },
  // 切换中英文
  switchLanguage(e) {
    let {
      name
    } = e.currentTarget.dataset;
    app.globalData.language = name;
    this.updateLanguage();
  },
  // 更新语言
  updateLanguage() {
    this.setData({
      currentLanguage: app.globalData.language,
      languageData: JSON.parse(JSON.stringify(pageLanguage[app.globalData.language].formPage))
    })
  },
  // 协议change
  agreementChange(e) {
    this.setData({
      isAgreement: e.detail
    })
  },
  // form-item数据change
  updateValue(e) {
    let name = e.currentTarget.dataset.inputName,
      value = e.detail || '';
    this.setData({
      [name]: value
    });
  },
  // 发送验证码
  async sendCode() {
    if (codeTime) {
      return
    }
    if (!/^\d{11}$/g.test(this.data.formData.tel)) {
      Toast(pageLanguage[app.globalData.language].formPageToast.checkTel)
      return;
    }
    //loading
    Toast.loading({
      message: pageLanguage[app.globalData.language].formPageToast.loadingSend,
      forbidClick: true,
      duration: 0
    });

    try {
      await ajaxSendMessage({
        tel: this.data.formData.tel,
        //  注册1 登录2
        smsType: 2
      })
      this.setData({
        codeNum: 59
      })
      codeTime = setInterval(() => {
        let newCodeNum = this.data.codeNum - 1;
        if (newCodeNum <= 0) {
          clearInterval(codeTime)
          codeTime = null
        }
        this.setData({
          codeNum: newCodeNum
        })
      }, 1000)
      await app.myNextTick()
      Toast.clear();
      Toast(pageLanguage[app.globalData.language].formPageToast.codeSendOk)
    } catch (err) {
      await app.myNextTick()
      Toast.clear();
      Toast(err.msg || pageLanguage[app.globalData.language].formPageToast.error)
    }
  },
  // 校验数据
  isCheck(isShowMsg = false) {
    let {
      formData,
      isAgreement
    } = this.data;
    // if (!formData.surnames) {
    //   return {
    //     result: false,
    //     msg: pageLanguage[app.globalData.language].formPageToast.checkSurname
    //   };
    // }
    // if (!formData.name) {
    //   return {
    //     result: false,
    //     msg: pageLanguage[app.globalData.language].formPageToast.checkName
    //   };
    // }
    if (!/^\d{11}$/g.test(formData.tel)) {
      return {
        result: false,
        msg: pageLanguage[app.globalData.language].formPageToast.checkTel
      };
    }
    if (!formData.msgCode) {
      return {
        result: false,
        msg: pageLanguage[app.globalData.language].formPageToast.checkCode
      };
    }
    if (!isAgreement) {
      return {
        result: false,
        msg: pageLanguage[app.globalData.language].formPageToast.checkAgreement
      };
    }
    return {
      result: true,
      msg: 'ok'
    };
  },
  // 查询账号
  async queryAccountLayer() {
    let {
      result,
      msg
    } = this.isCheck(true)
    if (!result) {
      Toast(msg)
      return;
    }
    //loading
    Toast.loading({
      message: pageLanguage[app.globalData.language].formPageToast.processing,
      forbidClick: true,
      duration: 0
    });
    try {
      let {
        data
      } = await ajaxGetTelUsers({
        tel: this.data.formData.tel
      });
      let userList = data || [];
      if (userList.length) {
        // 只有一个账号自动登录
        if (userList.length == 1) {
          this.setData({
            'formData.k1UserId': userList[0].k1UserId,
            'accountLayer.show': false,
          })
          this.submit();
        } else {
          // 多个账号显示选择弹层选择登录
          this.setData({
            'formData.k1UserId': null,
            'accountLayer.show': true,
            'userList': userList
          })
        }
      }
      await app.myNextTick()
      Toast.clear();
      // 没有查询到账号
      if (!userList.length) {
        Toast.fail('无账号');
      }
    } catch (err) {
      await app.myNextTick()
      Toast.clear();
      Toast(err.msg || pageLanguage[app.globalData.language].formPageToast.error)
    }
  },
  // 提交
  async submit(e) {
    let {
      result,
      msg
    } = this.isCheck(true)
    if (!result) {
      Toast(msg)
      return;
    }

    if (!this.data.formData.k1UserId) {
      Toast(pageLanguage[app.globalData.language].formPageToast.checkUserId)
      return;
    }

    try {
      await app.initLogin(this.data.formData);
      // 清空验证码
      this.setData({
        'formData.msgCode': ''
      })
      // 登录成功跳转到首页
      app.commonToPage('/pages/home/index', 'switchTab', {}, () => {
        wx.showToast({
          title: pageLanguage[app.globalData.language].formPageToast.loginOk,
          icon: 'success',
          duration: 2000
        })
      })
    } catch (err) {
      // 清空验证码
      this.setData({
        'formData.msgCode': ''
      })
    }
  },
  // 去注册协议页面
  goAgreements() {
    app.commonNavigateTo('/pages/agreements/register/index')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.currentLanguage != app.globalData.language) {
      this.updateLanguage();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (checkTime) {
      clearTimeout(checkTime)
      checkTime = null;
    }
    if (codeTime) {
      clearInterval(codeTime)
      codeTime = null
    }
  }
})